$(function () {
    $("body").on("click","#course-list-context .fa-gavel-btn",function () {//单个完结课程
        var courseId = $(this).data("id");
        updateContextStatus(courseId);
    }).on("click",".fa-arrow-up",function () {//单个上架课程
        var courseId = $(this).parent().data("id");
        updateCourseStatus(courseId,1);
    }).on('click','#saveOnShelf',function () {//套餐设置课程页面上架
        var id = $(this).data('id');
        updateCourseStatus(id,1,true);
    }).on('click',".fa-arrow-down",function () {//单个下架课程
        var courseId = $(this).parent().data("id");
        updateCourseStatus(courseId,2);
    }).on('click',"#course-list-context .fa-trash-remove-bt",function () {//单个删除课程
        var courseId = $(this).data("id");
        updateCourseStatus(courseId,3);
    }).on('click',"#onBatch",function () {//批量上架
        updateCourseStatus(getChecked(1),1);
    }).on('click',"#offBatch",function () {//批量下架
        updateCourseStatus(getChecked(2),2);
    }).on('click',"#finishBatch",function () {//批量完结
        updateContextStatus(getChecked(4));
    }).on('click',"#deleteBatch",function () {//批量删除
        updateCourseStatus(getChecked(3),3);
    }).on('click', '#course-list-context .courseAttrShow', function () { //课程详情查看(不含章节)
        var parentEm = $(this);
        var courseId = parentEm.data('id');
        var courseTypeKey = parentEm.data('type');
        var courseName = parentEm.data('name');
        var title ;
        if(courseTypeKey == "PACKAGE"){
            title = '查看套餐';
        }else{
            title = '查看课程';
        }
        parent.layer.open({
            area: winArea,
            btn: ['进入修改状态', '取消'],
            content: baseloaction + "/admin/course/cou/previewCourse?courseId=" + courseId + '&courseType=' + courseTypeKey,
            maxmin: true,
            shade: [0.3, '#000'],
            shadeClose: false,
            title: title +'[<small>' + courseName + '</small>]',
            type: 2,
            yes: function (index) {
                if(courseTypeKey == "PACKAGE"){
                    window.location = baseloaction + '/admin/course/cou/initUpdatePackage?id=' + courseId + '&courseType=' + courseTypeKey;
                }else{
                    window.location = baseloaction + '/admin/course/cou/initUpdate?id=' + courseId + '&courseType=' + courseTypeKey;
                }
                parent.layer.close(index);
            },success:function (layero,index) {
                var _iframe = $(layero).find("iframe:visible");
                var openMaterials= $(_iframe[0]).contents().find('li.openMaterial');
                console.log(openMaterials);
                for(var i=0;i<openMaterials.length;i++){
                    $(openMaterials[i]).on('click',function(){
                        openMateria( $(this).find('span').data('id'));
                    });
                }
            }
        })
    });

    /**
     * 修改课程状态（删除、上架、下架）
     * @param courseIds
     * @param status
     */
    function updateCourseStatus(courseIds,status,type) {
        var courseTypeKey = $('#courseTypeKey').val();
        var message = '';
        if(status==1){//上架
            message = '确认要上架课程？';
        }else if(status==2){//下架
            message = '可能会影响此课程相关联的数据哦，确认要下架吗？';
        }else if(status==3){//删除
            message = '可能会影响此课程相关联的数据哦，确认要删除吗？';
        }
        if (!courseIds) {
            icModale(0, '请选择要操作的课程');
            return;
        }
        if(courseIds=='-1'){
            if(status==2){
                icModale(0, '所选课程已下架，操作无效');
                return;
            }else if(status==1){
                icModale(0, '所选课程已上架，操作无效');
                return;
            }else{
                icModale(0, '发布过的课程不可删除');
                return;
            }
        }
        if(courseIds=="w"){//所选记录都为未上架课程，无法执行下架操作
            icModale(0, '所选课程全部为未上架，操作无效');
            return;
        }
        icModale(2, message, 3, function () {
            $.ajax({
                url:baseloaction +'/admin/course/cou/updateCourseStatus',
                type:'post',
                data:{
                    'courseIds':courseIds,
                    'status':status
                },
                success:function (result) {
                    icModale(0, result.message);
                    if(result.success==true){
                        var idArr = (courseIds+"").split(",");
                        $.each(idArr,function (index,id) {
                            if(id!=null && $.trim(id)!=''){
                                var statusEm = $("#status-"+id);
                                var statusAction = $("#status-action-"+id);
                                if(status == 1){
                                    statusEm.html('<span class="label label-info">已上架</span>');
                                    statusAction.html('<i class="fa fa-arrow-down"></i>');
                                    statusAction.attr('data-original-title','下架');
                                    if(type==true){
                                        window.location.href = baseloaction +'/admin/course/package/toPackageCourseList';
                                    }
                                }
                                if(status ==2){
                                    statusEm.html('<span class="label label-danger">已下架</span>');
                                    statusAction.html('<i class="fa fa-arrow-up"></i>');
                                    statusAction.attr('data-original-title','上架');
                                }
                                if(status ==3){
                                    $("#course-data-"+id).remove();
                                }
                            }
                        });
                        if(status == 3){
                            listCourse(currentPage);
                            //updateCount((courseIds + '').split(',').length,status);
                        }
                        listCount(courseTypeKey);
                    }
                },
                error:function (error) {
                    icModale(0, '系统错误，操作失败');
                }
            });
        });
    }

    /**
     * 修改课程的完结状态
     * @param courseIds 课程ID串
     */
    function updateContextStatus(courseIds) {
        if (!courseIds) {
            icModale(0, '请选择要操作的课程');
            return;
        }
        if(courseIds=='-1'){
            icModale(0, '所选课程已完结，操作无效');
            return;
        }
        icModale(2, '完结后课程的目录章节将不可进行任何编辑操作，确认要完结选中的课程吗？', 3, function () {
            $.ajax({
                url:baseloaction +'/admin/course/cou/updateContextStatus',
                type:'post',
                data:{'courseIds':courseIds},
                success:function (result) {
                    if(result.success){
                        var idArr = (courseIds+"").split(",");
                        $.each(idArr,function (index,id) {
                            if(id!=null && $.trim(id)!=''){
                                $("#context-status-"+id).html('<span class="label label-info">已完结</span>');
                                $("#context-status-action-"+id).remove();
                            }
                        });
                        icModale(0, result.message);
                    }
                },
                error:function (error) {
                    icModale(0, '系统错误，设置课程完结失败');
                }
            })
        });
    }

    /**
     * 获得选中的记录id
     * @returns {string}
     */
    function getChecked(status) {
        var checked = $('#course-list-context input.i-checks:checked');
        var num = 0 ;
        var ids = checked.map(function () {
            var parent = $(this).parents('div');
            if (predicate(parent, status)) {
                return this.value;
            }else if(parent.find('.label-default-info').length > 0){
                num++;
            }
        }).get().join(',');

        if(checked.length==0){//未选中任何记录
            return '';
        }else {
            if(!ids){
                if(num==checked.length){//判断所选记录是否都为未上架
                    return "w";
                }else{
                    return '-1';
                }
            }else {
                return ids;
            }
        }
    }

    /**
     * 是否获取该条记录的id的谓词
     * @param parent tr元素
     * @param status 更新后的状态
     * @returns {boolean}
     */
    function predicate(parent, status) {
        switch (status) {
            case 1:
                return parent.find('i.fa-arrow-up').length > 0;
            case 2:
                return parent.find('i.fa-arrow-down').length > 0;
            case 3:
                return parent.find('i.fa-trash').length > 0;
            case 4:
                return parent.find('i.fa-gavel').length > 0;
            default:
                return false;
        }
    }

    /**
     * 更新统计总量
     * @param length
     */
    function updateCount(length) {
        var html = $('#totalNum').html();
        var regex = /[\d]+/g;
        var number = parseInt(regex.exec(html));
        number -= length;
        if (number == 0) $('div.noDataTipsBox').parents('tr').show();
        $('#totalNum').html(html.replace(regex, number));
    }

    function openMateria(materialId){
        parent.layer.open({
            area: ['800px', '500px'],
            btn: ['取消'],
            content: baseloaction + "/admin/course/material/showMaterialInfo?id=" + materialId,
            shade: [0.3, '#000'],
            shadeClose: false,
            title: '查看素材',
            type: 2
        });
    }
});